<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ActiveRecord
 *
 * @author Chris Sim
 */
class ActiveRecord extends CActiveRecord{
    //put your code here
    public function validateArray($validateRef) {
        $validate = true;
        if($validateRef  instanceof CActiveRecord)
            $validateRef = array($validateRef);
        foreach($validateRef as $_validateRef) {
            foreach($_validateRef as $ref) {
                if(!$ref->validate()) {
                    Yii::log("Cargo validating error", 'error', 'application.models.'.$ref);
                    $validate = false;
                }
            }
        }
        return $validate;
    }
    public function save2Many($model,$noempty=array(),$foreignID=array()) {
        
        if(!$this->isNewRecord) {
            foreach($model as $item) {
                foreach($foreignID as $k=>$v)
                    $item->$k = $this->$v;
                $found = true;
                foreach($noempty as $_empty) {
                    if(empty($item->$_empty))
                        $found = false;
                }
                if(!empty($item->id) && $item->findByPk($item->id))
                {
                    $item->isNewRecord = false;
                }
                if($found) {
                    if(!$item->save())
                        return false;
                }
            }
        }
        return true;
    }
	public function Add(&$model,$foreignKey){
    	if($this->isNewRecord)
    		return false;
    	$empty = true;    	
    	foreach($model->attributeNames() as $name) {
    		if(!empty($model->$name))
    			$empty = false;
    	}
    	if($empty)
    		return true;
    	if($model instanceof CActiveRecord) {
    		$model->$foreignKey = $this->getPrimaryKey();
    		return $model->save();
    	}
    	else
    		return false;
    }
    public function AddMany($model=array(), $foreignKey, $ValuetoKey = array()){
    	if(!is_array($model))
    		$model = array($model);
    	$_model = current($model);
    	$_model->deleteAll($foreignKey.' =:key',array(':key'=>$this->getPrimaryKey()));
    	foreach($model as $item){
    		foreach($ValuetoKey as $key=>$value){
    			$item->$key = $value;
    		}
            if(!$this->Add($item,$foreignKey))
            	return false;
        }
        return true;
    }
    public function AddLabel($topic,$msg) {
    	$model = new label;
    	$model->for_model = $this->tableName();
    	$model->foreign_key = $this->id;
    	$model->topic = $topic;
    	$model->desc = $msg;
    	$model->save();
    }
	public function generateRef($refCol,$id = null){
		if($id === null)
			$id = $this->getPrimaryKey();
		if($refCol == null)
			return;
		$this->$refCol = dechex(time().$id);
		$this->save();
    }
    public function saveManyMany($tableName,$colNdata) {

    }
}
?>
